package com.yang.springcloud.controller;

import com.yang.springcloud.lb.LoadBalancer;
import com.yang.springcloud.pojo.CommonResult;
import com.yang.springcloud.pojo.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

//    public static final String PAYMENT_URL = "http://localhost:8001";

    /** 引入 自定义 的 LB */
    @Autowired
    private LoadBalancer loadBalancer;

    @Autowired
    private DiscoveryClient discoveryClient;


    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }


    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/getForEntity/{id}")
    public CommonResult<Payment> getPaymentById2(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        if (entity.getStatusCode().is2xxSuccessful()){
            //这个 实体对象 中还包含其他很多信息
            log.info("{状态码: " + entity.getStatusCode() +
                    ", 头信息: " + entity.getHeaders() + "}");
            // 如果成功
            return entity.getBody();
        }else {
            return new CommonResult<>(444, "【查询失败】");
        }
    }


    /** 用于测试自定义负载均衡 */
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        // 根据 ServiceId 获取 Server 集合
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        // 如果没有服务
        if (instances == null || instances.size() <= 0){
            return null;
        }

        // 获取 Server 实例
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        // 通过实例获得该实例的 地址
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }


}
